/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dp1.pucp.Compras.VIsta;

import com.dp1.pucp.Administracion.Vista.*;
import com.dp1.pucp.Modelo.Clases.Maquina;
import com.dp1.pucp.Modelo.Clases.Pedidocompra;
import com.dp1.pucp.Modelo.Clases.Pedidocompra;
import com.dp1.pucp.Util.Validaciones;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

/**
 *
 * @author tupapi.com
 */
public class BuscarPedidoCompraGUI extends javax.swing.JDialog {

    private JTable tblResultados;
    private DefaultTableModel modelo;
    private JScrollPane scroll;
    private Border empty;
    private JFrame padre;

    public BuscarPedidoCompraGUI(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        setLocationRelativeTo(null);

        dtcFechaInicio.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                // the docs of JDateChooser says that when the date is modified, a "date" property change is fired 
                if (evt.getPropertyName().equals("date")) {
                    dtcFechaFin.setMinSelectableDate(dtcFechaInicio.getDate());
                }
            }
        });

        dtcFechaFin.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                // the docs of JDateChooser says that when the date is modified, a "date" property change is fired 
                if (evt.getPropertyName().equals("date")) {
                    dtcFechaInicio.setMaxSelectableDate(dtcFechaFin.getDate());
                }
            }
        });
    }

    public String getCodigo() {
        return txtCodigo.getText().trim();
    }

    public Date getFechaIni() {
        return dtcFechaInicio.getDate();
    }

    public Date getFechaFin() {
        return dtcFechaFin.getDate();
    }

    public void mostrarAviso(String msn) {
        Validaciones.mostrarMensajeAvisoVal(msn);
    }

    public void mostrarError(String msn) {
        Validaciones.mostrarMensajeErrorVal(msn);
    }
    /*public int solicitarConfirmacion(String msn){
     return Validaciones.solicitarConfirmacionVal(msn);
     }    */

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLayeredPane1 = new javax.swing.JLayeredPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtCodigo = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        dtcFechaInicio = new com.toedter.calendar.JDateChooser();
        dtcFechaFin = new com.toedter.calendar.JDateChooser();
        btnBuscar = new javax.swing.JButton();
        btnLimpiar = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        btnAsignarProv = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        panelTabla = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Buscar Pedido De Compra", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Ubuntu", 0, 15))); // NOI18N

        jLabel1.setText("Código:");

        txtCodigo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtCodigoKeyTyped(evt);
            }
        });

        jLabel5.setText("Fecha Solicitud:");

        jLabel2.setText("-");

        btnBuscar.setFont(new java.awt.Font("Ubuntu", 0, 10)); // NOI18N
        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/buscar.png"))); // NOI18N
        btnBuscar.setText("Buscar");
        btnBuscar.setBorderPainted(false);
        btnBuscar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnBuscar.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        btnBuscar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        btnLimpiar.setFont(new java.awt.Font("Ubuntu", 0, 10)); // NOI18N
        btnLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/clear.png"))); // NOI18N
        btnLimpiar.setText("Limpiar");
        btnLimpiar.setBorderPainted(false);
        btnLimpiar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnLimpiar.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        btnLimpiar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        jLabel3.setFont(new java.awt.Font("Ubuntu", 0, 12)); // NOI18N
        jLabel3.setText("A continuación se muestran los Pedido de Compra en estado \"Registrado\"");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(220, 220, 220)
                .addComponent(btnBuscar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnLimpiar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 467, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel5))
                                .addGap(26, 26, 26)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(dtcFechaInicio, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(1, 1, 1)
                                        .addComponent(dtcFechaFin, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                        .addGap(0, 29, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jSeparator2))
                        .addContainerGap())))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(8, 8, 8)
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(19, 19, 19)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(19, 19, 19)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(dtcFechaInicio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(dtcFechaFin, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        btnAsignarProv.setFont(new java.awt.Font("Ubuntu", 0, 10)); // NOI18N
        btnAsignarProv.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Activar.png"))); // NOI18N
        btnAsignarProv.setText("Siguiente");
        btnAsignarProv.setBorderPainted(false);
        btnAsignarProv.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAsignarProv.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        btnAsignarProv.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        btnCancelar.setFont(new java.awt.Font("Ubuntu", 0, 10)); // NOI18N
        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/cancel.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.setBorderPainted(false);
        btnCancelar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnCancelar.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        btnCancelar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        panelTabla.setLayout(new java.awt.BorderLayout());

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnAsignarProv)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnCancelar))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(panelTabla, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelTabla, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnAsignarProv)
                    .addComponent(btnCancelar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel1.getAccessibleContext().setAccessibleName("Buscar ");
        jPanel1.getAccessibleContext().setAccessibleDescription("");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
    }//GEN-LAST:event_btnBuscarActionPerformed

    //VALIDACIONES
    private void txtCodigoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoKeyTyped
        // TODO add your handling code here:
        String car = txtCodigo.getText();
        if (car.length() >= 25) {
            evt.consume();
        }
        Validaciones.soloDigitoTexto(evt);
    }//GEN-LAST:event_txtCodigoKeyTyped

    // FIN VALIDACIONES
    public void LimpiarDatos() {
        txtCodigo.setText("");
        dtcFechaInicio.setDate(null);
        dtcFechaFin.setDate(null);

    }

    public void addBuscarListener(ActionListener ml) {
        this.btnBuscar.addActionListener(ml);
    }

    public void addCancelarListener(ActionListener ml) {
        this.btnCancelar.addActionListener(ml);
    }

    public void addLimpiarListener(ActionListener ml) {
        this.btnLimpiar.addActionListener(ml);
    }

    public void addAsignarProvListener(ActionListener ml) {
        this.btnAsignarProv.addActionListener(ml);
    }

    public void realizarFiltro(ArrayList<Pedidocompra> lista) {
//        ((DefaultTableModel) this.tblResultados.getModel()).setRowCount(0);
        ArrayList<Pedidocompra> listPedido = new ArrayList<>();
        String codigo = txtCodigo.getText();
        Date fechaIni = dtcFechaInicio.getDate();
        Date fechaFin = dtcFechaFin.getDate();

        if (lista.size() == 0) { //Esto es si es q en la base de datos no hay ninguna orden guardada
            mostrarAviso("No se ha registrado ningun Pedido de Compra");
        } else {
            //veo si es que puso algun codigo, si es que si solo mostrará una orden unica
            if (!(codigo.equals(""))) {
                for (int i = 0; i < lista.size(); i++) {
                    if (codigo.equals(lista.get(i).getCodigo())) {
                        listPedido.add(lista.get(i));
                    }
                }
            } else {
                //Para comprobar con las fechas
                if (((fechaIni != null) & (fechaFin == null)) || (fechaIni == null) & (fechaFin != null)) {
                    mostrarError("Debe ingresar un rango de fechas");
                    return;
                }

                if ((fechaIni != null) & (fechaFin != null)) {
                    for (int i = 0; i < lista.size(); i++) {
                        if (fechaIni.before(lista.get(i).getFechasolicitud()) & (lista.get(i).getFechasolicitud().before(fechaFin))) {
                            listPedido.add(lista.get(i));
                        }
                    }
                    this.llenaGrilla(listPedido);
                    return;
                } else {
                    this.llenaGrilla(lista);
                    return;
                }
            }



            this.llenaGrilla(listPedido);

        }
        return;
    }

    public void llenaGrilla(ArrayList<Pedidocompra> listPedidocompra) {
        panelTabla.removeAll();
        TitledBorder tituloResultado = BorderFactory.createTitledBorder(empty, "Resultado:");
        tituloResultado.setTitleJustification(TitledBorder.LEFT);
        panelTabla.setBorder(BorderFactory.createTitledBorder("Resultados"));
        panelTabla.updateUI();
        if (listPedidocompra != null) {
            if (!listPedidocompra.isEmpty()) {
                modelo = new DefaultTableModel() {
                    @Override
                    public boolean isCellEditable(int fila, int columna) {
                        return false;
                    }
                };

                modelo.setRowCount(listPedidocompra.size());
                Object nombreCols[] = new Object[4];
                nombreCols[0] = "";
                nombreCols[1] = "Código";
                nombreCols[2] = "Fecha Solicitud";
                nombreCols[3] = "Estado";
                modelo.setColumnIdentifiers(nombreCols);


                for (int i = 0; i < listPedidocompra.size(); i++) {
                    if (i < 9) {
                        modelo.setValueAt("0" + (i + 1), i, 0);
                    } else {
                        modelo.setValueAt(i + 1, i, 0);
                    }
                    modelo.setValueAt(listPedidocompra.get(i).getCodigo(), i, 1);
                    modelo.setValueAt(listPedidocompra.get(i).getFechasolicitud(), i, 2);

                    if (listPedidocompra.get(i).getEstado() == 0) {
                        modelo.setValueAt("Cancelado", i, 3);
                    }
                    if (listPedidocompra.get(i).getEstado() == 1) {
                        modelo.setValueAt("Registrado", i, 3);
                    }
                    if (listPedidocompra.get(i).getEstado() == 2) {
                        modelo.setValueAt("Pendiente", i, 3);
                    }
                    if (listPedidocompra.get(i).getEstado() == 3) {
                        modelo.setValueAt("Recibido", i, 3);
                    }

                }

                tblResultados = new JTable();
                tblResultados.setDragEnabled(false);
                tblResultados.setModel(modelo);
                TableColumn tcol = tblResultados.getColumn("");
                tcol.setPreferredWidth(30);
                tcol.setMinWidth(30);
                tcol.setMaxWidth(30);
                tblResultados.getColumnModel().getColumn(0).setCellRenderer(tblResultados.getTableHeader().getDefaultRenderer());
                tblResultados.setEnabled(true);
                tblResultados.setRowSelectionAllowed(true);
                scroll = new JScrollPane(tblResultados);
                panelTabla.add(scroll);

            } else {
                panelTabla.removeAll();
                panelTabla.setBorder(empty);
                Validaciones.mostrarMensajeAvisoVal("No se encontraron resultados.");
            }
        } else {
            panelTabla.removeAll();
            panelTabla.setBorder(empty);
            Validaciones.mostrarMensajeAvisoVal("No se encontraron resultados.");
        }

        panelTabla.updateUI();
    }

//    public void llenaGrilla(ArrayList<Pedidocompra> lista) {
//        if (lista != null) {
//            if (lista.size() == 0) {
//                mostrarAviso("No se encuentra ningún Pedido de Compra Registrado bajo este criterio");
//            } else {
//                ((DefaultTableModel) this.tblResultados.getModel()).setRowCount(0);
//                for (int i = 0; i < lista.size(); i++) {
//                    ((DefaultTableModel) tblResultados.getModel()).setRowCount(tblResultados.getRowCount() + 1);
//                    tblResultados.setValueAt(lista.get(i).getCodigo(), i, 0);
//                    tblResultados.setValueAt(lista.get(i).getFechasolicitud(), i, 1);
//
//                    if (lista.get(i).getEstado() == 0) {
//                        tblResultados.setValueAt("Cancelado", i, 2);
//                    }
//                    if (lista.get(i).getEstado() == 1) {
//                        tblResultados.setValueAt("Registrado", i, 2);
//                    }
//                    if (lista.get(i).getEstado() == 2) {
//                        tblResultados.setValueAt("Pendiente", i, 4);
//                    }
//                    if (lista.get(i).getEstado() == 3) {
//                        tblResultados.setValueAt("Recibido", i, 4);
//                    }
//                }
//            }
//        }
//    }
    public int getFilaSel() {
        if (tblResultados != null) {
            return tblResultados.getSelectedRow();
        } else {
            return -1;
        }
    }

    public JFrame getPadre() {
        return padre;
    }
//    
//    public void addCancelarListener(ActionListener ml){
//        this.btnCancelar.addActionListener(ml);
//    } 
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAsignarProv;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnLimpiar;
    private com.toedter.calendar.JDateChooser dtcFechaFin;
    private com.toedter.calendar.JDateChooser dtcFechaInicio;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLayeredPane jLayeredPane1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JPanel panelTabla;
    private javax.swing.JTextField txtCodigo;
    // End of variables declaration//GEN-END:variables
}
